package com.lin.servlet;

import com.lin.pojo.User;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * SessionServlet: Session会话管理
 *      Session会话信息存放于服务器端, 且为每个Session设置一个SessionID, 客户端通过SessionID与服务器端通信
 *
 *      所谓Session，就是服务器与客户端之间会话的建立, 可用于保存用户会话信息(放到Cookies中)
 *          比如: 登录一个网站后, 再次访问网站不需要重新登陆,
 *              就算关闭浏览器重新启动浏览器, 都可以继续使用之前的登录信息
 *              前提: 如果Session设置了过期时间, 超时就要重新登录, 清理缓存同理
 */
public class SessionServlet2 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置编码
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;UTF-8");

        PrintWriter writer = resp.getWriter();

        // 获取Session会话信息
        HttpSession session = req.getSession();
        String sessionId = session.getId();
        System.out.println("sessionID: " + sessionId);

        writer.write("username: " + sessionId + "\n");
        User user = (User) session.getAttribute("user");
        System.out.println("user: " + user);

        if (user == null) {
            writer.write("the object you want to get is null!");
        } else {
            writer.write("user: " + user);
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
